package com.siyoumi.component.auth_img;

import com.siyoumi.component.XRedis;
import com.siyoumi.component.auth_img.entity.AuthImgData;
import com.siyoumi.util.XFile;
import com.siyoumi.util.XReturn;
import lombok.Getter;
import lombok.Setter;

import java.awt.image.BufferedImage;
import java.util.List;

public abstract class AuthImgService {
    @Getter
    @Setter
    String redisKey;


    /**
     * 获取验证图片
     *
     * @param data
     */
    public abstract List<BufferedImage> getImgInfo(AuthImgData data);

    public List<BufferedImage> getImgInfo() {
        AuthImgData data = AuthImgData.getInstance(null);
        return getImgInfo(data);
    }

    /**
     * 验证
     *
     * @param data
     */
    public abstract XReturn auth(AuthImgData data);

    public XReturn auth(String code) {
        return auth(AuthImgData.getInstance(code));
    }

    /**
     * 记录缓存
     *
     * @param val
     */
    protected void setRedisVal(String val) {
        XRedis.getBean().setEx(getRedisKey(), val, 60);
    }

    protected String getRedisVal() {
        return XRedis.getBean().getAndDel(getRedisKey());
    }

    /**
     * 验证初始化
     */
    final public XReturn authInit() {
        AuthImgData data = new AuthImgData();
        List<BufferedImage> imgInfo = getImgInfo(data);

        XReturn r = XReturn.getR(0);

        int index = 0;
        for (BufferedImage item : imgInfo) {
            //输出base64
            r.setData("img_" + index, XFile.toImgBase64(item));
            index++;
        }

        return r;
    }
}
